/*
 * @Author: Marte
 * @Date:   2016-10-28 10:07:12
 * @Last Modified by:   Marte
 * @Last Modified time: 2016-11-04 15:21:29
 */

'use strict';

var oracledb = require('../utils/oracleUtil');
var fs = require('fs');
var path = require('path');
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
var moment = require('moment')

var _ = require('underscore');
var Promise = require('bluebird');

var controller = {

};

var resourcePath;

if (process.env.NODE_ENV === 'development') {
    resourcePath = '/resource_dev';
} else {
    resourcePath = '/resource';
}


var range = function(start, end) {
    var array = [];
    for (var i = start; i < end; ++i) {
        array.push(i);
    }
    return array;
};

/**
 * [postUploadfileToJson 上传图片到服务器(文件保存为二进制字段)]
 * @param  {[type]}   req  [description]
 * @param  {[type]}   res  [description]
 * @param  {Function} next [description]
 * @return {[type]}        [description]
 */
controller.postUploadfileToJson = function(req, res, next) {
    //存放的目录对应为 /resource
    //console.log(req);
    var fileData = req.files.file;
    var filePath = fileData.path;
    var originalFilename = fileData.originalFilename;
    if (originalFilename) {
        var filetype = fileData.type.split('/')[0];
        var imagetype = fileData.type.split('/')[1];

        fs.readFile(filePath, function(err, data) {
            if (err) {
                return next(err);
            }

            //重命名为年月日时间（精确到1毫秒）
            var randomstr = range(0, 3).map(function(x) {
                return Math.floor(Math.random() * 10);
            }).join('');
            var fileFullName = moment().format('YYMMDDHHmmssSSS') + randomstr + '.' + imagetype;
            var fileName = (originalFilename.lastIndexOf('.') > 0) ? originalFilename.substring(0, originalFilename.lastIndexOf('.')) : originalFilename;
            var conn;
            //保存到数据库
            oracledb.connection()
                .then(function(connection) {
                    conn = connection;
                    return conn.execute('Insert Into pic(id,fileName,fileFullName,origName,fileData) ' + 'Values(pic_seq.nextval,:fileName,:fileFullName,:origName,:fileData)', {
                        fileName: fileName,
                        fileFullName: fileFullName,
                        origName: originalFilename,
                        fileData: data
                    });
                })
                .then(function() {
                    return conn.execute('Select id,fileName,fileFullName,fileData From pic Where fileFullName=:fileFullName and origName=:origName', {
                        fileFullName: fileFullName,
                        origName: originalFilename
                    });
                })
                .then(function(_rows) {
                    var row = _rows.rows[0];
                    conn.close();
                    return res.status(200).json({
                        ID: row.ID,
                        FILENAME: row.FILENAME,
                        FILEFULLNAME: row.FILEFULLNAME
                    });
                })
                .catch(function(err) {
                    conn.close();
                    return res.status(500).json({
                        error: '保存到数据库失败.',
                        syserror: err.message
                    });
                });
        });

    } else {
        res.status(400).json({
            error: '无效的文件'
        });
    }

};

/**
 * [getPicImage 显示图片]
 * @param  {[type]}   req  [description]
 * @param  {[type]}   res  [description]
 * @param  {Function} next [description]
 * @return {[type]}        [description]
 */
controller.getPicImage = function(req, res, next) {
    var picId = parseInt(req.params.id);
    var conn;
    if (picId) {
        oracledb.connection()
            .then(function(_conn) {
                conn = _conn;
                return conn.execute('Select fileData From pic Where id=:id', {
                    id: picId
                })
            })
            .then(function(result) {
                console.log(result);
                if (result.rows.length === 0) {
                    return Promise.reject(new Error('文件记录已不存在'));
                } else {
                    var lob = result.rows[0].FILEDATA;
                    //console.log(lob);
                    if (lob === null) {
                        Promise.reject(new Error('错误的文件！'));
                    } else {
                        lob.on(
                            'end',
                            function() {
                                console.log("lob.on 'end' event");
                                //console.log(res);
                                res.end();
                            });
                        lob.on(
                            'close',
                            function() {
                                console.log("lob.on 'close' event");
                                conn.release(function(err) {
                                    if (err) console.error(err);
                                });
                            });
                        lob.on(
                            'error',
                            function(err) {
                                console.log("lob.on 'error' event");
                                console.error(err);
                            });
                        res.writeHead(200, { 'Content-Type': 'image/jpeg' });
                        lob.pipe(res);
                    }
                }
            })
            .catch(function(err) {
                conn.release();
                res.status(500).json({
                    error: '读取图片失败',
                    syserror: err.message
                })
            });
    } else {
        res.status(400).json({
            error: '错误的参数',
            syserror: 'Invalid Parameter!'
        })
    }
};

/**
 * [deletePic 删除图片]
 * @param  {[type]}   req  [description]
 * @param  {[type]}   res  [description]
 * @param  {Function} next [description]
 * @return {[type]}        [description]
 */
controller.deletePic = function(req, res, next) {
    var picId = req.params.id;
    var fileFullName = null;
    if (picId) {
        var conn;
        oracledb.connection()
            .then(function(connection) {
                conn = connection;
                return conn.execute('select * From pic Where id=:id', [picId]);
            })
            .then(function(pic) {
                console.log(pic);
                if (pic.rows && pic.rows.length > 0) {
                    fileFullName = pic.rows[0].FILEFULLNAME;
                    //console.log('数据库删除');
                    return conn.execute('Delete From pic Where id=:id', { id: picId });
                }
            })
            .then(function() {
                return res.status(200).json({ success: 'OK' });
            })
            .catch(function(err) {
                conn.close();
                return res.status(500).json({
                    error: '删除失败.',
                    syserror: err.message
                });
            });
    } else {
        res.status(400).json({
            error: '错误的参数'
        });
    }
};

controller.registerPath = function(router) {

    //获取相片资源
    /*    router.addPathGetHanlder('/api/pics', controller.getAllJson);*/

    /*上传文件并保存到数据库*/
    router.addPathPostHanlder('/pics/uploadFiles', multipartMiddleware, controller.postUploadfileToJson);

    /*显示图片*/
    router.addPathGetHanlder('/resource/:id', controller.getPicImage);

    /*删除文件记录*/
    router.addPathDeleteHanlder('/pics/:id', controller.deletePic);


};

module.exports = controller;

/**
 * [getAllJson 获取相片]
 * @param  {[type]}   req  [
 * start:记录开始位置,
 * size:查找记录数,
 * countall:是否要计算总记录数
 * ]
 * @param  {[type]}   res  [json]
 * @param  {Function} next [description]
 * @return {[type]}        [{count:Number,rows:Array}]
 */
/*controller.getAllJson = function(req, res, next) {
    var offset = null;
    if (req.query.start) {
        offset = parseInt(req.query.start);
    }
    var size = null;
    if (req.query.size) {
        size = parseInt(req.query.size);
    }
    var s = req.query.search;

    var countall = 0;
    if (req.query.countall) {
        countall = parseInt(req.query.countall);
    }

    var getPic;
    if (countall) {
        getPic = Pic.fetchPageJsonAndCountAll(offset,
            size, s);
    } else {
        getPic = Pic.fetchPageJson(offset, size, s);
    }
    getPic
        .then(function(_result) {
            if (countall) {
                return res.json(_result);
            } else {
                return res.json({
                    rows: _result
                });
            }
        })
        .catch(function(err) {
            return res.status(500).json({
                error: '无法读取数据',
                syserror: err.message
            });
        })
        .error(function(err) {
            return res.status(400).json({
                error: '无法读取数据',
                syserror: err.message
            });
        });
};*/

/**
 * [postUploadfileToServer 上传图片到服务器(保存文件)]
 * @param  {[type]}   req  [description]
 * @param  {[type]}   res  [description]
 * @param  {Function} next [description]
 * @return {[type]}        [description]
 */
/*controller.postUploadfileToServer = function(req, res, next) {
    //存放的目录对应为 /resource
    //console.log(req);
    var fileData = req.files.file;
    var filePath = fileData.path;
    var fileSize = fileData.size;
    var originalFilename = fileData.originalFilename;

    if (originalFilename) {

        var filetype = fileData.type.split('/')[0];
        var imagetype = fileData.type.split('/')[1];

        fs.readFile(filePath, function(err, data) {
            if (err) {
                return next(err);
            }

            if (Buffer.isBuffer(data)) {
                console.log(data);
            }
            //重命名为年月日时间（精确到1毫秒）
            var randomstr = range(0, 3).map(function(x) {
                return Math.floor(Math.random() * 10);
            }).join('');
            var fileFullName = moment().format('YYMMDDHHmmssSSS') + randomstr + '.' + imagetype;
            var newPath = path.join(process.cwd(), resourcePath, fileFullName);
            var fileName = (originalFilename.lastIndexOf('.') > 0) ? originalFilename.substring(0, originalFilename.lastIndexOf('.')) : originalFilename;
            fs.writeFile(newPath, data, function(err) {
                if (err) {
                    return res.status(400).json({
                        error: '文件保存失败.',
                        syserror: err
                    });
                }
                console.log(filePath);
                var conn;
                //保存到数据库
                oracledb.connection()
                    .then(function(connection) {
                        conn = connection;
                        console.log(oracledb.autoCommit);
                        return conn.execute('Insert Into pic(id,fileName,fileFullName,origName) ' + 'Values(pic_seq.nextval,:fileName,:fileFullName,:origName)', {
                            fileName: fileName,
                            fileFullName: fileFullName,
                            origName: originalFilename
                        });
                    })
                    .then(function() {
                        return conn.execute('Select * From pic Where fileFullName=:fileFullName and origName=:origName', {
                            fileFullName: fileFullName,
                            origName: originalFilename
                        });

                    })
                    .then(function(_rows) {
                        conn.close();
                        return res.status(200).json(_rows.rows[0]);
                    })
                    .catch(function(err) {
                        conn.close();
                        return res.status(500).json({
                            error: '保存到数据库失败.',
                            syserror: err
                        });
                    });
            });
        });

    } else {
        res.status(400).json({
            error: '无效的文件'
        });
    }

};*/
